package com.suotuo.common.advice;

import com.suotuo.common.annotation.LogAnnotation;
import com.suotuo.module.sys.entity.SysLog;
import com.suotuo.module.sys.service.LogService;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author liulubingjava@163.com
 * @date 2019/1/23 16:24
 */
@Aspect
@Component
public class LogAdvice {
    @Autowired
    private LogService logService;
    @Around(value = "@annotation(com.suotuo.common.annotation.LogAnnotation)")
    public Object logSave(ProceedingJoinPoint joinPoint) throws Throwable {
        SysLog sysLog = new SysLog();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String module;
        LogAnnotation logAnnotation = methodSignature.getMethod().getDeclaredAnnotation(LogAnnotation.class);
        module = logAnnotation.moudle();
        if (StringUtils.isEmpty(module)) {
            ApiOperation apiOperation = methodSignature.getMethod().getDeclaredAnnotation(ApiOperation.class);
            if (apiOperation != null) {
                module = apiOperation.value();
            }
        }
        if (StringUtils.isEmpty(module)) {
            throw new RuntimeException("没有指定日志module");
        }
        sysLog.setModule(module);

        try {
            Object object = joinPoint.proceed();
            sysLog.setFlag(true);
            logService.save(sysLog);
            return object;
        } catch (Exception e) {
            sysLog.setFlag(false);
            sysLog.setRemark(e.getMessage());
            logService.save(sysLog);
            throw e;
        }
    }
}
